#define _WIN32_DCOM
#include <windows.h>
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#include <io.h>
#include <sys/stat.h>
#include "Component\component.h"

HRESULT IPToHexString(REFIID riid, IUnknown* pObject, char** output)
{
	HRESULT hr;
	IStream* pStream = 0;
	hr = CreateStreamOnHGlobal(0, TRUE, &pStream);

	hr = CoMarshalInterface(pStream, riid, pObject, MSHCTX_DIFFERENTMACHINE, 0, MSHLFLAGS_NORMAL);

	ULONG size;
	hr = CoGetMarshalSizeMax(&size, riid, pObject, MSHCTX_DIFFERENTMACHINE, 0, MSHLFLAGS_NORMAL);

	HGLOBAL hg;
	hr = GetHGlobalFromStream(pStream, &hg);
	unsigned char* buffer = (unsigned char*)GlobalLock(hg);

	*output = (char*)CoTaskMemAlloc((size * 2) + 1);

	char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
	
	for(ULONG count = 0; count < size; count++)
	{
		(*output)[count*2] = hex[buffer[count] / 16];
		(*output)[(count*2)+1] = hex[buffer[count] - (buffer[count] / 16) * 16];
	}
	(*output)[((count-1)*2)+2] = 0;

	GlobalUnlock(hg);
	pStream->Release();

	return hr;
}

void main()
{
	CoInitializeEx(NULL, COINIT_MULTITHREADED);

	HRESULT hr;
	ISum* pSum;
	hr = CoCreateInstance(CLSID_InsideCOM, NULL, CLSCTX_INPROC_SERVER, IID_ISum, (void**)&pSum);

	char* output;
	IPToHexString(IID_ISum, pSum, &output);

	int fh = _creat("c:\\ip.txt", _S_IWRITE);
	_write(fh, output, strlen(output));
	_close(fh);

	printf("%s\n", output);

	CoTaskMemFree(output);

	int addition;
	pSum->Sum(23, 32, &addition);
	cout << "23 + 32 = " << addition << endl;

	_getch();

	pSum->Release();

	CoUninitialize();
}